<?php
class FormModel extends Model {
	public function createForm($view){
		$data = $this -> find();
		$fieldDB = M('Field');
		$field_list = $fieldDB -> where(array('form_id' => $data['id'])) -> select();
		//生成字段的表单元素
		foreach($field_list as $k => $v){
			$view -> assign('field_'.$v['id'], fieldDispose($v));
		}
		

		if(!$data){
			return '';
		}

		
		return '<form class="guestbookdataform" enctype="multipart/form-data" action="'.U('Home/Mission/insert').'" method="post"><input type="hidden" name="form_id" value="'.$data["id"].'">'.$view -> fetch('','<span></span>'.$data['template']).'
		</form>';
	}
	// $type 是否生成HTML，1生成HTML，0生成纯字符（用于结果查看和信息提示）
	public function createTaskForm($view, $formdata = NULL, $createselectlist = 1, $type = 1){
		$data = $this -> find();
		$fieldDB = M('Field');
		$ruleDB=M('Integral_rule');
		$ruletypeDB=M('Integral_type');
		$field_list = $fieldDB -> where(array('form_id' => $data['id'])) -> select();
		//生成字段的表单元素
		foreach($field_list as $k => $v){
			if(in_array($v['f_type'], array(9,10,11,12)) && !empty($formdata)){
				$v['f_name'] .= '_id';
			}
			$view -> assign('field_'.$v['id'], fieldDisposebootstrap($v, $view, isset($formdata[$v['f_name']]) ? $formdata[$v['f_name']] : NULL, $createselectlist, $type));
		}
		if(!$data){
			return '';
		}
		$task_id = '';
		if(isset($_GET['task_id']) && intval($_GET['task_id']) > 0){
			$task_id = '<input type="hidden" name="task_id" value="'.intval($_GET['task_id']).'">';
		}
		if(isset($_GET['pid']) && intval($_GET['pid']) > 0){
			$task_id .= '<input type="hidden" name="pid" value="'.intval($_GET['pid']).'">';
		}
		
		if($type!=2){	
			//如果只是胜来n
			//生成一行多个的特殊规则块
			$source=unserialize($data['ruleidsource']);
			$rulehtml = '';
			if(!empty($data['ruleidsource'])){
				foreach($source as $kk=>$vv){
					$rulehtml.='<div class="form-inline icheck"><label class="groupName">'.$vv['name'].'：</label>';
					//如创建表的时候有设置分值，则为指定值    $v['rule'][0]是规则ID  如出现$v['rule'][1]则是设置的分数
					foreach($vv['rule'] as $ke=>$vo){
						$rule=$ruleDB->where(' ( id='.$vo[0].' or rid='.$vo[0].') and site_id = '.__SITEID__)->find();
						if(!empty($vo[1])){
							$rule['integralnum']=$rule['integralnum']<intval($vo[1])?$rule['integralnum']:intval($vo[1]);
						}
						$name='integral['.$kk.'][]';
						$datahtml='';
						$checked='';
						if(isset($formdata['integral'])){
							foreach($formdata['integral'][$kk] as $value){//&&$formdata['integral'][$k][$ke==0?0:$ke/2]['id']==$vo[0]
								$checked=$value['id']==$vo[0]?'checked':$checked.' '.$value;
							}
						}
						//循环遍历出积分源的积分隐藏域
						if(!empty($rule['source'])){
							$rulesource=unserialize($rule['source']);
							foreach($rulesource as $key=>$value){
								
								if(empty($value[0])){continue;}
								if(isset($value[1])){
									$ruletype=$ruletypeDB->where('typename=\''.$key.'\'')->getField('remark');
									$datahtml.='<label class="hidden pull-left">'.$ruletype.'：</label><input datatype="num" type="number" class="sourceInput hidden form-control pull-right" style="width:auto; display:inline;" maxlength="5" min="'.$value[0].'" disabled max="'.$value[1].'" errormsg="超出规定数值" name="integral['.$rule['id'].']['.$key.']" value="'.$value[0].'"/><br/>';
								}else{
									$value=$value[0];	
									$datahtml.='<div><input class="sourceInput" disabled type="hidden" name="integral['.$rule['id'].']['.$key.']" value="'.$value.'"/></div>';
								}
								
							}
						}
						//如果规则暂时还没有积分域则使用默认积分
						if(empty($datahtml)){
							$datahtml='<div><input class="sourceInput" data-type="Binte" disabled type="hidden" name="integral['.$rule['id'].'][Binte]" value="'.$rule['integralnum'].'"/></div>';
						}
						//并给区间分数加上显示框
						if(strpos($datahtml,'number')>0){
							$datahtml='<div class="sourcePanel">'.$datahtml.'</div>';
						}
						$rulehtml.='<label class="checkbox-inline" title="'.$rule['remark'].'"><div class="'.$vv['type'].' square-red single-row"><label><input class="intesysRule '.$checked.'" '.$checked.' type="'.$vv['type'].'" value="'.$vo[0].'" name="'.$name.'[id]">'.$rule['name'].'</label>'.$datahtml.'</div></label>';
						
					}
					$rulehtml.='</div>';
				}
				
			}
			
			
			$ruleids = explode(',', trim($data['ruleids'], ','));
			if(trim($data['ruleids'], ',') == ''){
				$ruleids = array(0);
			}
			$rules =  $ruleDB-> where("id in(".implode(',', $ruleids).")") -> select();

			//生成一行一个的规则
			foreach($rules as $key => $val){
				if($data['rulecheck'] == 0){
					if(isset($formdata['integral_rule_id']) && $formdata['integral_rule_id'] == $val['id']){
						$checked = 'checked="checked"';
					}else{
						$checked = '';
					}
					if($key == 0){
						$rulehtml .= '<input type="hidden" value="'.$formdata['integral_rule_id'].'" name="integral_rule_id" id="integral_rule_id">';
					}
					$rulehtml .= '<div style="padding:1px 5px; background:#fff;"><label class="checkbox" style="display:block;  margin-bottom:5px; margin-right:15px;"><input id="'.$val['integralnum'].'" value="'.$val['integralnum'].'" onClick="document.getElementById(\'integral_rule_id\').value='.$val['id'].'" name="rule" '.$checked.' type="radio" nullmsg="" datatype="*" errormsg=""><span>'.$val['name'].'</span><span class="text-'.($val['integralnum'] >= 0?'success':'danger').' pull-right">'.$val['integralnum'].'分</span>';
		if(trim($val['remark']) != ''){
			$rulehtml .= '<p style="font-size:9px;">备注：'.$val['remark'].'</p>';
		}
		  $rulehtml .= '
		</label></div><hr>'; 
				}else{
					if(isset($formdata['integral_rule_id']) && in_array($val['id'], $formdata['integral_rule_id'])){
						$checked = 'checked="checked"';
						$disabled = '';
					}else{
						$disabled = 'disabled';
						$checked = '';
					}
					$rulehtml .= '<input type="hidden" name="integral_rule_id[]" value="'.$val['id'].'" '.$disabled.' id="integral_rule_id'.$val['id'].'"><div style="padding:1px 5px; background:#fff;"><label class="checkbox" style="display:block;  margin-bottom:5px; margin-right:15px;"><input onClick="if(this.checked){document.getElementById(\'integral_rule_id'.$val['id'].'\').disabled=false;}else{document.getElementById(\'integral_rule_id'.$val['id'].'\').disabled=true;}" id="'.$val['integralnum'].'" value="'.$val['integralnum'].'" name="rule[]" type="checkbox" nullmsg="" datatype="*" '.$checked.' errormsg=""><span>'.$val['name'].'</span><span class="text-'.($val['integralnum'] >= 0?'success':'danger').' pull-right">'.$val['integralnum'].'分</span>';
		if(trim($val['remark']) != ''){
			$rulehtml .= '<p style="font-size:9px;">备注：'.$val['remark'].'</p>';
		}
		  $rulehtml .= '
		</label></div><hr>';
				}
			}
		}
		
		return '<div class="hidden OptionTitle">'.$data['name'].'</div>
<div class="hidden OptionBtn">保存</div><style>form.opacity td{padding:5px;}form.opacity hr{margin:5px;}</style><form data-intro="操作表单" data-position="top" class="checkoutform opacity" enctype="multipart/form-data" action="'.U('Intesys/Taskform/saveform').'" method="post">
<input type="hidden" name="formula" value="'.$data['formula'].'">
'.$rulehtml.$task_id.'<input type="hidden" value="'.$data['approver'].'" name="approver"><input type="hidden" value="'.$data['approvername'].'" name="approvername"><input type="hidden" name="form_id" value="'.$data["id"].'">'.$view -> fetch('','<!-- -->'.$data['template']).'
		<input type="hidden" id="_sendtype" name="status" value="-1"></form>';
	}
	
	//复制数据
	public function copy($siteid, $tositeid,$map,$category_id = 0){
		$re=$this->where($map)->order('id')->select();
		$FieldDB = M('Field');
		if($re!==false){ 
			foreach($re as $k=>$v){
				$v['site_id'] = $tositeid;
				$v['rid'] = $v['id'];
				$fields = $FieldDB -> where(array('form_id' => $v['id'])) -> select();
				unset($v['id']);
				$id = $this->data($v)->add();
				//复制字段 
				$template['template'] = $v['template'];
				$template['formula'] = $v['formula'];
				$template['formcategory_id'] = $category_id;
				foreach($fields as $key => $val){
					$val['rid'] = $val['id'];
					unset($val['id']);
					$val['form_id'] = $id;
					$val['site_id']=$tositeid;
					$fid = $FieldDB -> add($val);
					$template['template'] = str_replace('{$field_'.$val['rid'].'}','{$field_'.$fid.'}', $template['template']);
					$template['formula'] = str_replace('{$field_'.$val['rid'].'}','{$field_'.$fid.'}', $template['formula']);
					
				}
				$this->where(array('id' => $id))->data($template) -> save();
			}
			return true;
		}
	}

	
}